package com.gnerv.cms.freemarker.tag;

import com.gnerv.cms.dto.SiteDTO;
import com.gnerv.cms.dto.SiteSearchDTO;
import com.gnerv.cms.freemarker.FreemarkerComponent;
import com.gnerv.cms.service.ISiteService;
import com.gnerv.cms.utils.FreemarkerUtils;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/4/3
 */
@FreemarkerComponent("g_site")
public class SiteTagDirective implements TemplateDirectiveModel {

    @Resource
    private ISiteService siteService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        SiteSearchDTO siteSearchDTO = new SiteSearchDTO();
        String code = FreemarkerUtils.getParamToString("code", map);
        if (!StringUtils.isEmpty(code)) {
            siteSearchDTO.setCode(code);
        }
        String name = FreemarkerUtils.getParamToString("name", map);
        if (!StringUtils.isEmpty(name)) {
            siteSearchDTO.setName(name);
        }
        SiteDTO siteDTO = siteService.selectSite(siteSearchDTO);
        TemplateModel tm = builder.build().wrap(siteDTO);
        environment.setVariable("site", tm);
        templateDirectiveBody.render(environment.getOut());
    }

}
